# -*- coding:utf8 -*-
from __future__ import print_function, unicode_literals
import sys
from json import dumps

SEP = ""


def rprint(data, indent=0, end='\n', file_=sys.stdout, sorted_=False):
    """
    针对嵌入的数据结构，打印出较好排版的格式
    """
    indent_str = '  ' * indent
    indent_str_1 = '  ' * (indent + 1)

    if isinstance(data, dict):
        print(indent_str, '{', sep=SEP, file=file_)

        tmp = data.items()
        if sorted_:
            tmp = sorted(tmp)

        for key, value in tmp:
            print(indent_str_1, key, ':', sep=SEP, file=file_)
            rprint(value, indent + 2, end=',\n', file_=file_)

        print(indent_str, '}', end=end, file=file_)

    elif isinstance(data, (tuple, list)):
        print(indent_str, '[', sep=SEP, file=file_)

        if sorted_:
            data = sorted(data)
        for value in data:
            rprint(value, indent + 1, end=',\n', file_=file_)

        print(indent_str, ']', end=end, file=file_)

    else:
        print(indent_str, data, end=end, sep=SEP, file=file_)


def format_byjson(data):
    """
    通过json对数据结构进行格式化
    :param data: 
    :return: 
    """
    str_ = dumps(data, indent=2, ensure_ascii=False, encoding='utf8')
    return str_


def rprint_json(data):
    """
    直接使用json进行解析输出
    :param data: 
    :return: 
    """
    print(format_byjson(data))


if __name__ == '__main__':
    tmp = {
        '测试': '测试',
        '脚本': [
            '脚本',
            '脚本'
        ]
    }

    from pprint import pprint
    pprint(tmp, indent=2, depth=4)
    rprint_json(tmp)